//
//  HHLoginWithAuthorCodeViewController.m
//  HHBroker
//
//  Created by He Wei on 9/22/15.
//  Copyright © 2015 harry. All rights reserved.
//

#import "HHLoginWithAuthCodeViewController.h"
#import "HHLoginWithPhoneNavi.h"
#import "HHTimerButton.h"
#import "HttpRequestManager.h"
#import "NSString+ValidateArgument.h"

@interface HHLoginWithAuthCodeViewController ()

@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, copy) NSString *authorCode;
@property (nonatomic, weak) IBOutlet UIView *codeView;
@property (nonatomic, weak) IBOutlet UILabel *phoneLabel;
@property (nonatomic, weak) IBOutlet UIButton *returnButton;
@property (nonatomic, weak) IBOutlet UITextField *authorCodeTextField;
@property (nonatomic, weak) IBOutlet HHTimerButton *timerButton;


@end

@implementation HHLoginWithAuthCodeViewController

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"短信验证码登录";
    NSString *phone = [self.readAuthorCodePhone stringByReplacingCharactersInRange:NSMakeRange(4, 4) withString:@"****"];
    self.phoneLabel.text = phone;
    [self.timerButton addTarget:self action:@selector(timerButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelButtonClicked:)];
    self.navigationItem.rightBarButtonItem = cancelButton;
    
}

#pragma mark - Event
- (IBAction)textFieldValueChanged:(UITextField *)textField
{
    self.returnButton.enabled = textField.text.length > 0 ? YES : NO;

}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    [self.view endEditing:YES];

}
- (void)timerButtonClicked:(HHTimerButton *)button
{
    __block MBProgressHUD *hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hub.mode = MBProgressHUDModeIndeterminate;
    hub.labelText = NSLocalizedString(@"正在获取验证码", nil);;
    //网络请求
    //加入 加密字段
    
    NSString *encPhone = self.readAuthorCodePhone;
    NSString *urlString = [NSString stringWithFormat:@"%@&username=%@", KUrlLoginGetCode, encPhone];
    [HttpRequestManager getWithUrlString:urlString success:^(id response) {
        NSInteger code = [[response objectForKey:@"code"] integerValue];
        if (code == 1) {
            //sent success
            button.timeOut = 60;
            UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"alert_success"]];
            hub.mode = MBProgressHUDModeCustomView;
            hub.labelText = NSLocalizedString(@"发送成功，请查看短信", nil);;
            hub.completionBlock = ^ {
                [self.authorCodeTextField becomeFirstResponder];
            
            };
            [hub hide:YES afterDelay:1];
        } else {
            NSString *msgString = [response objectForKey:@"msg"];
            hub.mode = MBProgressHUDModeText;
            hub.labelText = msgString;
            [hub hide:YES afterDelay:1];
        }
    
    } failure:^(NSError *error){
        [hub hide:YES];
        hub.mode = MBProgressHUDModeText;
        hub.labelText = NSLocalizedString(@"网络好像有点问题", nil);;
        [hub hide:YES afterDelay:1];
    
    } isLogin:NO];

}

- (IBAction)returnAuthorCodeButtonClicked:(UIButton *)sender
{
    [self.view endEditing:YES];
    
    //检查输入
    NSString *authorCode = self.authorCodeTextField.text;
    authorCode = [authorCode stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if (![NSString validateAuthorCode:authorCode]) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"验证码不正确，请重新输入" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        return;
    }
    __block MBProgressHUD *hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hub.mode = MBProgressHUDModeIndeterminate;
    hub.labelText = @"正在提交验证码";
    //网络请求
    //加入加密字段
    NSString *encPhone = self.readAuthorCodePhone;
    NSString *urlString = [NSString stringWithFormat:@"%@&username=%@&code=%@", KUrlLoginCheckCode, encPhone, authorCode];

    [HttpRequestManager getWithUrlString:urlString success:^(id response) {
        NSInteger code = [[response objectForKey:@"code"] integerValue];
        hub.mode = MBProgressHUDModeText;
        hub.labelText = [response objectForKey:@"msg"];
        if (code == 1) {
            //验证通过
            hub.mode = MBProgressHUDModeText;
            hub.labelText = @"登录成功";
            hub.completionBlock = ^ {
                HHLoginWithPhoneNavi *rootVC = (HHLoginWithPhoneNavi *)self.navigationController;
                
                NSParameterAssert([rootVC isKindOfClass:[HHLoginWithPhoneNavi class]]);
                if ([rootVC.delegate respondsToSelector:@selector(loginWithPhoneViewController:didFinishLoginWithResponse:)]) {
                    [rootVC.delegate loginWithPhoneViewController:rootVC didFinishLoginWithResponse:response];
                }
                
            
            };
        } else {
        
        }
        [hub hide:YES afterDelay:1];
    
    
    }failure:^(NSError *error) {
        hub.labelText = @"网络有点问题";
        [hub hide:YES afterDelay:2];
    
    
    } isLogin:NO];

}

- (void)cancelButtonClicked:(UIBarButtonItem *)item
{
    SEL selector = NSSelectorFromString(@"loginWithPhoneViewController:didCancelWithResult:");
    if ([self.navigationController.delegate respondsToSelector:selector]) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        [self.navigationController.delegate performSelector:selector withObject:self.navigationController];
#pragma clang diagnostic pop
        
    }
}





@end
